import settings from '@/settings'
import { jsonp } from 'vue-jsonp'
import { getCityList } from '@/api/film'
import { getStorageItem, setStorageItem } from '@/utils/storage'

const cityListKey = 'cityList'

const getDefaultState = () => {
  return {
    currentLocation: null,
    currentCity: null,
    cityList: getStorageItem(cityListKey) || []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_CURRENT_CITY: (state, city) => state.currentCity = city,
  SET_CITY_LIST: (state, list) => state.cityList = list,
  SET_CURRENT_LOCATION: (state, location) => state.currentLocation = location,
}

const actions = {
  // 获取当前定位城市
  async getCurrentCity({ dispatch }) {
    const city = await dispatch('getLocationCity')

    const cityList = await dispatch('getCityList')
    
    return dispatch('findCurrentCity', { cityList, city })
  },
  // 城市列表查询当前城市
  findCurrentCity({ commit }, { cityList, city }) {
    console.log('正在从城市列表获取当前城市')
    const currentCity = cityList.find(({ regionName }) => {
      return city.search(regionName) > -1
    }) || settings.defaultCityInfo
    console.log('当前城市', currentCity)
    commit('SET_CURRENT_CITY', currentCity)
    return currentCity
  },
  // 获取城市列表
  async getCityList({ commit, state }) {
    console.log('正在从缓存获取城市列表')
    const cityList = state['cityList']
    if (!cityList.length) {
      console.log('缓存不存在城市列表，将从服务器获取')
      const { data } = await getCityList()
      commit('SET_CITY_LIST', data.list)
      setStorageItem(cityListKey, data.list)
      return data.list
    }
    return cityList
  },
  // 定位获取当前城市
  async getLocationCity({ commit, dispatch }) {
    try {
      console.log('正在获取定位')
      const { ip, location, ad_info } = await dispatch('getQQLocation')
      console.log(`定位获取的城市：${ad_info.city}`)
      commit('SET_CURRENT_LOCATION', { ip, ...location })
      return ad_info.city
    } catch (error) {
      console.log(`定位失败，默认城市为${settings.defaultCityInfo.regionName}`)
      return settings.defaultCityInfo.regionName
    }
  },
  // 第三方获取位置信息（含经纬度）
  getQQLocation() {
    return new Promise((resolve, reject) => {
      jsonp(`${settings.wsUrl}/ws/location/v1/ip`, {
        key: settings.wsKey,
        output: 'jsonp'
      }).then(function (response) {
        if (response.status !== 0) {
          reject(new Error(response.message))
        } else {
          console.log('定位数据', response.result)
          resolve(response.result)
        }
      }).catch(function (error) {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

